package com.example.lj.uav.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.adapter.RouteAdapter;
import com.example.lj.uav.bean.RouteLine;
import com.example.lj.uav.dao.MyDBDao;
import com.example.lj.uav.utils.CEComplexComparator;
import com.example.lj.uav.utils.ComparatorUtils;
import com.example.lj.uav.utils.TimeUtils;
import com.example.lj.uav.view.RouteMenuActivity;
import com.example.lj.uav.view.RouteSettingActivity;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FragmentRouteMenuCollection extends Fragment implements View.OnClickListener, Handler.Callback {
    private RecyclerView mRev;
    private RouteAdapter adapter;
    private List<RouteLine> lineList = new ArrayList<>();
    private MyDBDao dao;
    private RouteMenuActivity mActivity;
    private TextView mTv;
    public int selectedQty = 0;
    private RouteAdapter searchAdapter;
    private List<RouteLine> searchList = new ArrayList<>();
    private Handler handler;
    private List<String> fileNames = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_collection, container, false);
        mTv = view.findViewById(R.id.tv_no_collected_route);
        mRev = view.findViewById(R.id.rev_route_collection);
        dao = MyApplication.dao;
        handler = new Handler(this);
        mActivity = (RouteMenuActivity) getActivity();
        initView();
        return view;
    }

    private void initView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        mRev.setLayoutManager(gridLayoutManager);
    }

    @Override
    public void onResume() {
        super.onResume();
        getLineData();
    }

    public void getLineData() {
        List<RouteLine> lines = dao.queryCollectedRoute();
        if (lines == null || lines.size() == 0) {
            mRev.setVisibility(View.GONE);
            mTv.setVisibility(View.VISIBLE);
            return;
        }
        fileNames = mActivity.getFileNames();
        if (adapter == null) {
            adapter = new RouteAdapter(lineList, handler);
            adapter.headerShow = false;//不显示header
            adapter.isSearching = true;//不显示可选择功能
            mRev.setAdapter(adapter);
            mRev.setVisibility(View.VISIBLE);
            mTv.setVisibility(View.GONE);
        }
        lineList.clear();
        lineList.addAll(lines);
        Collections.sort(lineList, new TimeUtils());
        adapter.notifyDataSetChanged();
        mActivity.updateButtonStatus(lineList.size());
    }

    public void onSearchButtonPressed(String fileName) {
        searchList.clear();
        Pattern pattern = Pattern.compile(fileName);
        for (int i = 1; i < lineList.size(); i++) {
            String name = lineList.get(i).getFileName();
            Matcher matcher = pattern.matcher(name);
            if (matcher.find()) {
                searchList.add(lineList.get(i));
            }
        }
        if (searchList.size() <= 0) {
            mActivity.searchNoData();
            mRev.setVisibility(View.GONE);
        } else {
            mActivity.searHasData();
            mRev.setVisibility(View.VISIBLE);
        }
        searchAdapter.notifyDataSetChanged();
    }

    public void listByTime() {
        Collections.sort(lineList, new TimeUtils());
//        lineList.add(new RouteLine());
        adapter.notifyDataSetChanged();
    }

    public void listByName() {
        //判断
        for (int i = 0; i < lineList.size(); i++) {
            String fileName = lineList.get(i).getFileName();
            String f = fileName.substring(0, 1);
            if (ComparatorUtils.containChinese(f)) {
                try {
                    String fpinyin = PinyinHelper.getShortPinyin(f);
                    int code = ComparatorUtils.SumStrAscii(fpinyin);
                    lineList.get(i).setFileNameCode(code);
                } catch (PinyinException e) {
                    e.printStackTrace();
                }
            } else if (ComparatorUtils.isEnglish(fileName)) {
                String first = fileName.substring(0, 1);
                int code = ComparatorUtils.SumStrAscii(first);
                lineList.get(i).setFileNameCode(code);
            } else {
                String first = fileName.substring(0, 1);
                int firstNo = Integer.parseInt(first);
                lineList.get(i).setFileNameCode(firstNo);
            }
        }
        Collections.sort(lineList, new CEComplexComparator());
//        lineList.add(new RouteLine());
        adapter.notifyDataSetChanged();
    }

    public void showAllTypeRoute() {
        onSearchCanceled();
    }

    public void showAreaTypeRoute() {
        searchList.clear();
        searchList.add(new RouteLine());
        if (searchAdapter == null) {
            searchAdapter = new RouteAdapter(searchList, handler);
            searchAdapter.isSearching = true;
        }
        searchAdapter.headerShow = false;
        mTv.setVisibility(View.GONE);
        mRev.setAdapter(searchAdapter);

        for (int i = 1; i < lineList.size(); i++) {
            if (lineList.get(i).getType().equals("area")) {
                searchList.add(lineList.get(i));
            }
        }
        searchAdapter.notifyDataSetChanged();
    }

    public void showLineTypeRoute() {
        searchList.clear();
        searchList.add(new RouteLine());
        if (searchAdapter == null) {
            searchAdapter = new RouteAdapter(searchList, handler);
            searchAdapter.isSearching = true;
        }
        searchAdapter.headerShow = false;
        mTv.setVisibility(View.GONE);
        mRev.setAdapter(searchAdapter);

        for (int i = 1; i < lineList.size(); i++) {
            if (lineList.get(i).getType().equals("line")) {
                searchList.add(lineList.get(i));
            }
        }
        searchAdapter.notifyDataSetChanged();
    }

    public void onSearchMenuPressed() {
        searchList.clear();
        if (searchAdapter == null) {
            searchAdapter = new RouteAdapter(searchList, handler);
            searchAdapter.isSearching = true;
        }
        searchAdapter.headerShow = false;
        mTv.setVisibility(View.GONE);
        mRev.setAdapter(searchAdapter);
    }

    public void onSearchCanceled() {
        searchList.clear();
        searchAdapter.notifyDataSetChanged();
        mRev.setAdapter(adapter);
        mRev.setVisibility(View.VISIBLE);
        if (lineList.size() == 0) {
            mTv.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case RouteAdapter.ROUTE_SELECTED:
                int position = message.arg1;
                RouteLine line = lineList.get(position);
                List<String> namesNew = new ArrayList<>();
                namesNew.addAll(fileNames);
                namesNew.set(position, "");
                Intent intent = new Intent(getActivity(), RouteSettingActivity.class);
                intent.putExtra("line", line);
                intent.putExtra("names", (Serializable) namesNew);
                intent.putExtra("start_flag", 1);
                intent.putExtra("name", line.getFileName());
                startActivity(intent);
                break;
            case RouteAdapter.ROUTE_CHECKED:
                selectedQty++;
                mActivity.mTvSelected.setText("已选" + selectedQty + "条");
                break;
            case RouteAdapter.ROUTE_CHECKED_CANCEL:
                selectedQty--;
                mActivity.mTvSelected.setText("已选" + selectedQty + "条");
                break;
        }
        return false;
    }

    public void selectButtonPressed() {
//        adapter.headerShow = false;
        adapter.isSearching = false;//不显示header但要可选择
//        lineList.remove(0);
        adapter.notifyDataSetChanged();
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
    }

    public void completeButtonPressed() {
//        adapter.headerShow = true;
//        List<RouteLine> list = new ArrayList<>();
//        list.add(new RouteLine());
//        list.addAll(lineList);
//        lineList.clear();
//        lineList.addAll(list);
//        adapter.notifyDataSetChanged();
        selectedQty = 0;
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
        getLineData();
    }

    public void collectButtonPressed() {
        for (int i = 0; i < lineList.size(); i++) {
            if (lineList.get(i).isChecked()) {
                if (lineList.get(i).getCollected() == 0) {
                    lineList.get(i).setCollected(1);
                } else {
                    lineList.get(i).setCollected(0);
                }
                dao.updateRoute(lineList.get(i), lineList.get(i).getFileName());
            }
        }
        getLineData();
        selectedQty = 0;
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
        mActivity.updateMenuList();
    }

    public void deleteButtonPressed() {
        List<RouteLine> list = new ArrayList<>();
        List<RouteLine> deleteList = new ArrayList<>();
        for (int i = 0; i < lineList.size(); i++) {
            if (!lineList.get(i).isChecked()) {
                list.add(lineList.get(i));
            } else {
                deleteList.add(lineList.get(i));
            }
        }
        lineList.clear();
        lineList.addAll(list);
        for (int i = 0; i < deleteList.size(); i++) {
            dao.deleteRoute(deleteList.get(i).getFileName());
        }
        selectedQty = 0;
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {

    }

    public void exportButtonPressed(String path) {

    }
}
